package test;

public class BlockQueue1 {

    private int size=0;
    private volatile int tail=0;
    private volatile int head=0;
    private String[] data=new String[1000];

    //入队
    public void deque(String str) throws InterruptedException {
        synchronized (this) {
            while(size==data.length) {
                this.wait();
            }
            data[tail++]=str;
            size++;
            if(tail==data.length) {
                tail=0;
            }
            this.notify();
        }
    }
    //出队列
    public String enque() throws InterruptedException {
        synchronized (this) {
            while(size==0) {
                this.wait();
            }
            String ret=data[head++];
            size--;
            if(head==data.length) {
                head=0;
            }
            this.notify();
            return ret;
        }
    }
    public static void main(String[] args) {
        BlockQueue1 queue=new BlockQueue1();
        Thread t1=new Thread(()->{
            while(true) {
                try {
                    String str=queue.enque();
                    System.out.println("消费者消费："+str);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2=new Thread(()->{
            int num=1;
            while(true) {
                try {
                    queue.deque(num+"");
                    System.out.println("生产者生产："+num);
                    num++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
        System.out.println("程序开始");
    }
}
